from marshmallow import Schema, fields, validate, validates, ValidationError
import re
from datetime import datetime

class PersonalInfoSchema(Schema):
    """个人信息模式"""
    gender = fields.Str(validate=validate.OneOf(['男', '女', '其他', '未知']), load_default='未知')
    title = fields.Str()
    specialties = fields.List(fields.Str())

class ContactInfoSchema(Schema):
    """联系信息模式"""
    phone = fields.Str()
    email = fields.Email()
    office = fields.Str()

class UserSchema(Schema):
    """用户模式"""
    username = fields.Str(required=True, validate=validate.Length(min=3, max=50))
    password = fields.Str(required=True, validate=validate.Length(min=6), load_only=True)
    email = fields.Email(required=True)
    phone = fields.Str()
    name = fields.Str(required=True)
    staffId = fields.Str()
    departmentId = fields.Str()
    role = fields.Str(required=True, validate=validate.OneOf(['admin', 'doctor', 'nurse', 'pharmacist', 'patient']))
    roles = fields.List(fields.Str())
    personalInfo = fields.Nested(PersonalInfoSchema)
    status = fields.Str(validate=validate.OneOf(['active', 'inactive']), load_default='active')

    def validate_phone(self, value, **kwargs):
        """验证手机号格式"""
        if value and not re.match(r'^\d{11}$', value):
            raise ValidationError('手机号格式不正确')
        return value

class UserUpdateSchema(Schema):
    """用户更新模式"""
    username = fields.Str(validate=validate.Length(min=3, max=50))
    password = fields.Str(validate=validate.Length(min=6), load_only=True)
    email = fields.Email()
    phone = fields.Str()
    name = fields.Str()
    staffId = fields.Str()
    departmentId = fields.Str()
    role = fields.Str(validate=validate.OneOf(['admin', 'doctor', 'nurse', 'pharmacist', 'patient']))
    roles = fields.List(fields.Str())
    personalInfo = fields.Nested(PersonalInfoSchema)
    status = fields.Str(validate=validate.OneOf(['active', 'inactive']))

    def validate_phone(self, value, **kwargs):
        """验证手机号格式"""
        if value and not re.match(r'^\d{11}$', value):
            raise ValidationError('手机号格式不正确')
        return value

class LoginSchema(Schema):
    """登录模式"""
    username = fields.Str(required=True)
    password = fields.Str(required=True)

class PasswordChangeSchema(Schema):
    """密码修改模式"""
    oldPassword = fields.Str(required=True)
    newPassword = fields.Str(required=True, validate=validate.Length(min=6))

class PasswordResetSchema(Schema):
    """密码重置模式"""
    newPassword = fields.Str(required=True, validate=validate.Length(min=6))

class UserQuerySchema(Schema):
    """用户查询模式"""
    username = fields.Str()
    role = fields.Str()
    departmentId = fields.Str()
    status = fields.Str() 